﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Model.WaiGaoQiao;
using WaiGaoQiaoWeb.Models;
using WaiGaoQiaoWeb.JsonEntities;
using AutoMapper;

namespace WaiGaoQiaoWeb.Controllers
{
    public class DeptManagementController : Controller
    {
        private DeptManagementInfo depinfo = new DeptManagementInfo();

        public ActionResult DeptManagementIndex()
        {
            return View();
        }

        public ActionResult SelDeptInfo()
        {
            IList<DeptManagementInfo> deptlist = depinfo.SelDeptInfo();
            List<JsonTreeNode> nodes = new List<JsonTreeNode>();
            foreach (var item in deptlist)
            {
                JsonTreeNode cnode = new JsonTreeNode();
                cnode.id = item.departmentid.ToString();
                cnode.text = item.departmentname;
                cnode.value = item.departmentno;
                cnode.hasChildren = false;
                cnode.classes = "system";
                cnode.isexpand = false;
                cnode.complete = true;
                AddChildNode(cnode);
                nodes.Add(cnode);
            }
            return Json(nodes);
        }

        /// <summary>
        /// 递归添加子节点
        /// </summary>
        /// <param name="node"></param>
        private void AddChildNode(JsonTreeNode node)
        {
            int pid = Convert.ToInt32(node.id);
            IList<DeptManagementInfo> mlist =
                depinfo.SelDeptChildInfo().Where(cinfo => cinfo.updepartmentid == pid).ToList();
            if (mlist != null)
            {
                foreach (var Childitem in mlist)
                {
                    node.hasChildren = true;
                    JsonTreeNode nodeChild = new JsonTreeNode();
                    nodeChild.id = Childitem.groupid.ToString();
                    nodeChild.text = Childitem.groupname;
                    nodeChild.value = Childitem.groupno;
                    nodeChild.hasChildren = false;
                    nodeChild.isexpand = true;
                    //AddChildNode(nodeChild);
                    node.ChildNodes.Add(nodeChild);
                }
            }
        }
    }
}
